package com.zhang.yygh.order.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.enums.PaymentStatusEnum;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderCountQueryVo;
import com.atguigu.yygh.vo.order.OrderCountVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.atguigu.yygh.vo.order.OrderQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhang.yygh.common.exception.YYGHException;
import com.zhang.yygh.hosp.client.HospitalFeignClient;
import com.zhang.yygh.mq.MqConst;
import com.zhang.yygh.mq.RabbitService;
import com.zhang.yygh.order.mapper.OrderInfoMapper;
import com.zhang.yygh.order.service.OrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhang.yygh.order.service.PaymentService;
import com.zhang.yygh.order.service.WeixinService;
import com.zhang.yygh.order.utils.HttpRequestHelper;
import com.zhang.yygh.user.client.UserFeignClient;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author zhang
 * @since 2022-03-16
 */
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private HospitalFeignClient hospitalFeignClient;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private WeixinService weixinService;

    @Autowired
    private PaymentService paymentService;

    @Override
    public Long submitOrder(String scheduleId, Long patientId) {
        //1.根据排班id获取排版信息
        ScheduleOrderVo schedule = hospitalFeignClient.getScheduleById(scheduleId);
        //2.根据就诊人id获取就诊人信息
        Patient patient = userFeignClient.getPatientById(patientId);
        //3.平台系统请求第三方医院系统，确认是否能够挂号

        //使用map集合封装需要传过医院数据
        //医院返回数据
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode",schedule.getHoscode());
        paramMap.put("depcode",schedule.getDepcode());
        paramMap.put("hosScheduleId",schedule.getHosScheduleId());
        paramMap.put("reserveDate",new DateTime(schedule.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", schedule.getReserveTime());
        paramMap.put("amount",schedule.getAmount()); //挂号费用

        //就诊人
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType",patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex",patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone",patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode",patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode",patient.getDistrictCode());
        paramMap.put("address",patient.getAddress());
        //联系人
        paramMap.put("contactsName",patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        //String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", "");

        JSONObject jsonObject = HttpRequestHelper.sendRequest(paramMap, "http://localhost:9998/order/submitOrder");
        //挂号成功
        //3.2 可以：①将上述三部分内容插入到order_info表中
        if (jsonObject!=null&&jsonObject.getIntValue("code")==200){
            // 如果医院接口返回成功，添加上面三部分数据到数据库
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setUserId(patient.getUserId());
            //服务器生成的一个唯一标识
            String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100);
            orderInfo.setOutTradeNo(outTradeNo);

            orderInfo.setHoscode(schedule.getHoscode());
            orderInfo.setHosname(schedule.getHosname());
            orderInfo.setDepcode(schedule.getDepcode());
            orderInfo.setDepname(schedule.getDepname());
            orderInfo.setTitle(schedule.getTitle());
            //排班编号
            orderInfo.setScheduleId(schedule.getHosScheduleId());
            //预约时间
            //预约上午/下午
            orderInfo.setReserveDate(schedule.getReserveDate());
            orderInfo.setReserveTime(schedule.getReserveTime());
            orderInfo.setPatientId(patientId);
            orderInfo.setPatientName(patient.getName());
            orderInfo.setPatientPhone(patient.getPhone());

            // 如果返回成功，得到返回其他数据
            JSONObject data = jsonObject.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = data.getString("hosRecordId");
            //预约序号
            Integer number = data.getInteger("number");
            //取号时间
            String fetchTime = data.getString("fetchTime");
            //取号地址
            String fetchAddress = data.getString("fetchAddress");

            //设置添加数据--医院接口返回数据
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            orderInfo.setAmount(schedule.getAmount());
            orderInfo.setQuitTime(schedule.getQuitTime());
            orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());

            baseMapper.insert(orderInfo);

            //②更新平台的可预约数和剩余可预约数的值
            Integer reservedNumber = data.getInteger("reservedNumber");
            Integer availableNumber = data.getInteger("availableNumber");

            OrderMqVo orderMqVo=new OrderMqVo();
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);
            orderMqVo.setScheduleId(scheduleId);
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(patient.getPhone());
            msmVo.setTemplateCode("您预约的时间是：${time},${when}该验证码5分钟内有效");

            Map<String, Object> map = new HashMap<>();
            map.put("time",schedule.getReserveDate());
            map.put("when",schedule.getReserveTime()==1?"下午":"上午");
            msmVo.setParam(map);

            orderMqVo.setMsmVo(msmVo);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,orderMqVo);

            //③给就诊人信息，提醒预约成功

            return orderInfo.getId();
        }else {
            //3.1 不可以：抛出异常
            throw new YYGHException(20001,"挂号失败");
        }


    }

    //实现列表
//（条件查询带分页）
    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo orderQueryVo) {
        //orderQueryVo获取条件值
        String name = orderQueryVo.getKeyword(); //医院名称
        Long patientId = orderQueryVo.getPatientId(); //就诊人名称
        String orderStatus = orderQueryVo.getOrderStatus(); //订单状态
        String reserveDate = orderQueryVo.getReserveDate();//安排时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();
        //对条件值进行非空判断
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("hosname",name);
        }
        if(!StringUtils.isEmpty(patientId)) {
            wrapper.eq("patient_id",patientId);
        }
        if(!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status",orderStatus);
        }
        if(!StringUtils.isEmpty(reserveDate)) {
            wrapper.ge("reserve_date",reserveDate);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        wrapper.eq("user_id",orderQueryVo.getUserId());
        //调用mapper的方法
        IPage<OrderInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        pages.getRecords().stream().forEach(item -> {
            this.packOrderInfo(item);
        });
        return pages;
    }

    @Override
    public OrderInfo getOrderInfo(Long orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        return this.packOrderInfo(orderInfo);
    }

    //取消预约
    @Override
    public void cancelOrder(Long orderId) {
        //1.首先要查看当前时间是否已经超过了当前订单所规定的退号时间，如果超过了，抛出异常，不让取消
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        Date quitTime = orderInfo.getQuitTime();
        DateTime dateTime = new DateTime(quitTime);
        if (dateTime.isBeforeNow()){
            throw new YYGHException(20001,"已经超过规定的退号时间");
        }

        //只有在已支付的情况下才完成退款
        if (orderInfo.getOrderStatus()==OrderStatusEnum.PAID.getStatus()){
            boolean flag=weixinService.refund(orderId);
            if (!flag){
                throw new YYGHException(20001,"退款失败");
            }
        }

        //2.如果没有超过，取消订单：
            //2.2 往退款记录表中添加数据
            //2.1 完成微信退款，更新退款记录表字段


            //2.3 更新订单状态及支付记录表的支付状态
        orderInfo.setOrderStatus(OrderStatusEnum.CANCLE.getStatus());
        baseMapper.updateById(orderInfo);

        PaymentInfo paymentInfo = new PaymentInfo();
        QueryWrapper<PaymentInfo> paymentInfoQueryWrapper = new QueryWrapper<>();
        paymentInfoQueryWrapper.eq("order_id",orderId);
        PaymentInfo one = paymentService.getOne(paymentInfoQueryWrapper);
        one.setPaymentStatus(PaymentStatusEnum.REFUND.getStatus());
        paymentService.updateById(one);
            //2.4 更新排版数据
        //发送mq信息更新预约数 我们与下单成功更新预约数使用相同的mq信息，不设置可预约数与剩余预约数，接收端可预约数减1即可
        OrderMqVo orderMqVo = new OrderMqVo();
        orderMqVo.setScheduleId(orderInfo.getScheduleId());
        //2.5 给就诊人发送短信提示信息
        //短信提示
        MsmVo msmVo = new MsmVo();
        msmVo.setPhone(orderInfo.getPatientPhone());
        orderMqVo.setMsmVo(msmVo);
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);

            //2.6 通知第三方医院
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("hosRecordId",orderInfo.getHosRecordId());
        JSONObject jsonObject = HttpRequestHelper.sendRequest(paramMap, "http://localhost:9998/order/updateCancelStatus");
        /*if (jsonObject.getInteger("code")!=200){
            paramMap.put("url","http://localhost:9998/order/updateCancelStatus");
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_HOSPITAL, MqConst.ROUTING_HOSPITAL_ITEM, paramMap);
        }*/

    }

    //定时提醒
    @Override
    public void patientTips() {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        String date = new DateTime().toString("yyyy-MM-dd");
        queryWrapper.eq("reserve_date",date);
        queryWrapper.ne("order_status",OrderStatusEnum.CANCLE.getStatus());
        List<OrderInfo> orderInfos = baseMapper.selectList(queryWrapper);
        for (OrderInfo orderInfo : orderInfos) {
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
            }};
            msmVo.setParam(param);
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SMS, MqConst.ROUTING_SMS_ITEM, msmVo);
        }
    }

    //统计预约信息
    @Override
    public Map<String, Object> countOrderInfo(OrderCountQueryVo orderQueryVo) {
        HashMap<String, Object> map = new HashMap<>();
        List<OrderCountVo> orderCountVos=baseMapper.countOrderInfo(orderQueryVo);
        //日期列表
        List<String> dateList =orderCountVos.stream().map(OrderCountVo::getReserveDate).collect(Collectors.toList());
        //统计列表
        List<Integer> countList =orderCountVos.stream().map(OrderCountVo::getCount).collect(Collectors.toList());
        map.put("dateList", dateList);
        map.put("countList", countList);
        return map;
    }

    private OrderInfo packOrderInfo(OrderInfo orderInfo) {
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }
}
